import 'dart:convert';
import 'package:black_movice/models/UserModel.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 本地数据存储类
class LocalStorage {
  static String userInfoKey = 'user_info';
  static String tokenKey = 'token';
  static String oneDayClear = 'one_day_clear'; //一天会清除的数据；

  static Future<void> setString(String key, dynamic value) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString(key, jsonEncode(value));
  }

  static Future<String?> getString(String key) async {
    try {
      SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      return sharedPreferences.getString(key);
    } catch (e) {
      return null;
    }
  }

  //移除
  static Future<bool?> removeString(String key) async {
    try {
      SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      return sharedPreferences.remove(key);
    } catch (e) {
      return null;
    }
  }

  //获取用户信息
  static Future<UserModel?> getUseInfo() async {
    try {
      String key = LocalStorage.userInfoKey;
      String? str = await LocalStorage.getString(key);
      Map<String, dynamic> map = jsonDecode(str!);
      UserModel userInfo = UserModel.fromJson(map);
      return userInfo;
    } catch (e) {
      return null;
    }
  }

  //清除用户信息
  static Future<bool?> removeUserInfo() async {
    try {
      return await LocalStorage.removeString(userInfoKey);
    } catch (e) {
      return null;
    }
  }

  static Future<String?> getToken() async {
    try {
      String? token = await LocalStorage.getString(tokenKey);
      if (token == null) return null;
      token = jsonDecode(token);
      return token;
    } catch (e) {
      return null;
    }
  }

  //清除token
  static Future<bool?> removeToken() async {
    try {
      return await LocalStorage.removeString(tokenKey);
    } catch (e) {
      return false;
    }
  }

  //清楚一天的数据
  static Future<void> clearCancel() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    Set<String> keys = sharedPreferences.getKeys();
    keys.forEach((key) async {
      if (key.contains(LocalStorage.oneDayClear)) {
        await sharedPreferences.remove(key);
      }
    });
  }
}
